package io.github.wppli.trigger.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import io.github.wppli.domain.posts.event.CalculatePostsTfIdfEvent;
import io.github.wppli.domain.posts.model.valobj.UserPostsBehaviorType;
import io.github.wppli.domain.posts.service.IPostsService;
import io.github.wppli.domain.recommond.model.entity.PostsContentEntity;
import io.github.wppli.domain.recommond.repository.IUserPostsBehaviorRepository;
import io.github.wppli.domain.recommond.rservice.IContentFeatureService;
import io.github.wppli.domain.recommond.rservice.text.TextFeatureService;
import io.github.wppli.types.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author li--jiaqiang 2025−03−16
 */
@Slf4j
@Component
public class CalculatePostsTfIdfCustomer {

    @Value("${spring.rabbitmq.topic.calculatePostsTFIDF}")
    private String topic;

    private final IPostsService postsService;
    private final TextFeatureService textFeatureService;
    private final IUserPostsBehaviorRepository userPostsBehaviorRepository;
    private final IContentFeatureService contentFeatureService;
    public CalculatePostsTfIdfCustomer(IPostsService postsService, TextFeatureService textFeatureService, IUserPostsBehaviorRepository userPostsBehaviorRepository, IContentFeatureService contentFeatureService) {
        this.postsService = postsService;
        this.textFeatureService = textFeatureService;
        this.userPostsBehaviorRepository = userPostsBehaviorRepository;
        this.contentFeatureService = contentFeatureService;
    }

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.calculatePostsTFIDF}"))
    public void listener(String message) {

        try {
            // 1. 转换对象
            BaseEvent.EventMessage<CalculatePostsTfIdfEvent.CalculatePostsTfIdfMessage> eventMessage =
                    JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<CalculatePostsTfIdfEvent.CalculatePostsTfIdfMessage>>() {
                    }.getType());
            CalculatePostsTfIdfEvent.CalculatePostsTfIdfMessage data = eventMessage.getData();
            Long contentId = data.getContentId();
            String content = data.getContent();
            UserPostsBehaviorType userPostsBehaviorType = data.getUserPostsBehaviorType();
            Long userId = data.getUserId();

            log.info("帖子TF-IDF任务，接收MQ消息成功 postsId:{} topic: {}", contentId, topic);
            // 2. 计算 TF-IDF 特征
            List<PostsContentEntity> allContents = postsService.queryAll();
            Map<String, Double> tfidf = textFeatureService.calculateTFIDF(content, allContents);
            try {
                log.info("监听用户取关-关注调整成功消息，进行取关-关注 topic: {} message: {}", topic, message);
                // 3. 存储 TF-IDF 特征（如保存到 Redis 或数据库）
                contentFeatureService.save(contentId, textFeatureService.toJson(tfidf));
                // 4. 存储用户对于该帖子的行为
                userPostsBehaviorRepository.save(userId, contentId, userPostsBehaviorType);
            } catch (Exception e) {
                log.error("存储 TF-IDF 特征，消费失败 contentId:{} topic: {} message: {}", contentId, topic, message);
                e.printStackTrace();
                // throw e;
            }
        } catch (Exception e) {
            log.error("帖子TF-IDF任务，接收MQ消息成功 topic:{} message: {}", topic, message);
            e.printStackTrace();
        }
    }
}